import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { increment } from './counterSlice';

// createAsyncThunk 创建异步状态， pending fulfilled rejected
const loadMovieAPI = () => {
    return fetch('https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id=2&ret_num=48&session=0d5d98d2fd37b7a71914a441c7c3b929')
    .then((res) => res.json());
}

// 此action可以直接调用，有三种状态
export const loadData = createAsyncThunk('movie/loadData', async () => {
    const res = await loadMovieAPI();
    return res;
})


export const movieSlice = createSlice({
    name: 'movie',
    initialState: {
        list: [],
        totals: 0
    },
    reducers: {
        loadDataEnd(state, { payload }) {
            state.list = payload;
            state.totals = payload.length;
        }
    },
    extraReducers: {
        [increment](state, payload) {
            state.list.push(1);
            state.totals += 1;
        },
        [loadData.fulfilled](state, { payload }) {
            console.log(payload);
            state.list = payload.data.list;
        },
        [loadData.rejected](state, err) {
            console.log(err);
        },
        [loadData.pending](state) {
            console.log('进行中');
        }
    }
})

export const { loadDataEnd } = movieSlice.actions;
export default movieSlice.reducer;